<?php

namespace App\Services\Upload;

use App\Models\Attachment;
use Auth;
use Exception;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\UploadedFile;
use OSS\Core\OssException;
use OSS\OssClient;

/**
 * 文件上传
 * @package App\Services
 */
class UploadService
{

    /**
     * 本地上传
     * @param UploadedFile $file
     * @return Attachment
     * @throws Exception
     * @throws BindingResolutionException
     */
    public function local($file)
    {
        if ($file instanceof UploadedFile) {
            $path = $file->store(date('Ym'), 'file');
            return self::save(url("/files/{$path}"), $file->getsize(), $file->getClientOriginalName(), $file->extension(), 'local');
        } else if (is_file($file)) {
            $info = pathinfo($file);
            $to = 'files/'.date('Ym').'/'.date('hms').'.'.$info['extension'];
            copy($file, public_path($to));
            return $this->save(url($to), filesize($file), basename($to), $info['extension'], 'local');
        }
    }

    /**
     * @param $file
     * @return mixed
     */
    public function localImage($file)
    {
        if ($file instanceof UploadedFile) {
            $path = $file->store(date('Ym'), 'attachment');
            return $this->save(url("/attachments/{$path}"), $file->getsize(), $file->getClientOriginalName(), $file->extension(), 'local');
        } else if (is_file($file)) {
            $info = pathinfo($file);
            $to = 'attachments/'.date('Ym').'/'.Auth::id().date('his').'.'.$info['extension'];
            copy($file, public_path($to));
            return $this->save(url($to), filesize($file), basename($to), $info['extension'], 'local');
        }
    }


    public function localImageBase64($content)
    {
        $pattern = '/(data:image\/)([^;]+)(;base64,)([^\"]+)/';
        $res = preg_replace_callback($pattern, function ($matches) {


            // 生成文件名
            $matches[2] = $matches[2] === 'jpeg' ? 'jpg' : $matches[2];
            //文件扩展名
            $extension = $matches[2];
//文件名
            $filename = md5(time().\Illuminate\Support\Str::random()).'.'.$matches[2];

            $info = pathinfo($filename);
//            路径
            $folder_path = 'attachments/'.date('Ym').'/'.date('his').'.'.$info['extension'];

            // 保存文件
            file_put_contents(public_path($folder_path), base64_decode($matches[4]));// base64 转图片

//            copy($filename, public_path($folder_path));
            // 返回相对路径

            return $this->save(url($folder_path), filesize(public_path($folder_path)), basename($folder_path), $extension, 'local');

        }, $content);
        return $res;
    }

    /**
     * 保存入库
     * @param mixed $path 文件链接
     * @param mixed $size 文件大小
     * @param mixed $name 源文件名
     * @param string|null $type 上传方式
     */
    protected static function save($path, $size, $name = null, $extension = null, string $type = null)
    {
        $attachment = Attachment::create([
            'path' => str_replace(config('app.url'), '', $path),
            'size' => $size,
            'type' => $type,
            'name' => $name,
            'extension' => $extension,
        ]);
        return $attachment;
    }

    /**
     * 删除文件
     * @param string $path
     * @return void
     */
    public function delete(?string $path)
    {
        $attachment = Attachment::where('path', $path)->first();
        if ($attachment) {
            $attachment->delete();
        }
        //从本地磁盘中删除文件
//        unlink()
    }


    /**
     *wangEditor图片上传
     */
    /**
     *
     * @param $file
     * @request
     * 返回格式：成功
     * {
     * "errno": 0, // 注意：值是数字，不能是字符串
     * "data": {
     * "url": "xxx", // 图片 src ，必须
     * "alt": "yyy", // 图片描述文字，非必须
     * "href": "zzz" // 图片的链接，非必须
     * }
     * }
     * 返回格式：失败
     * {
     * "errno": 1, // 只要不等于 0 就行
     * "message": "失败信息"
     * }
     */

    public function wangEditer($file)
    {
        if ($file instanceof UploadedFile) {
            $path = $file->store(date('Ym'), 'attachment');
            $res = self::save(url("/attachments/{$path}"), $file->getsize(), $file->getClientOriginalName(), $file->extension(), 'local');
            return [
                "errno" => 0, // 注意：值是数字，不能是字符串
                "data" => [
                    "url" => $res->path, // 图片 src ，必须
                    "alt" => "yyy", // 图片描述文字，非必须
                    "href" > $res->path // 图片的链接，非必须
                ]
            ];
        } else if (is_file($file)) {
            $info = pathinfo($file);
            $to = 'attachments/'.date('Ym').'/'.Auth::id().date('his').'.'.$info['extension'];
            copy($file, public_path($to));
            $res = $this->save(url($to), filesize($file), basename($to), $info['extension'], 'local');
            return [
                "errno" => 0, // 注意：值是数字，不能是字符串
                "data" => [
                    "url" => $res->path, // 图片 src ，必须
                    "alt" => "yyy", // 图片描述文字，非必须
                    "href" > $res->path // 图片的链接，非必须
                ]
            ];
        }
    }

    public function wxUpload($file)
    {
        if ($file instanceof UploadedFile) {
            $path = $file->store(date('Ym'), 'attachment');
            $res = self::save(url("/attachments/{$path}"), $file->getsize(), $file->getClientOriginalName(), $file->extension(), 'local');
            return [
                "status" => 'ok',
                "data" => $res->path,
                'result' => $res
            ];
        } else if (is_file($file)) {
            $info = pathinfo($file);
            $to = 'attachments/'.date('Ym').'/'.Auth::id().date('his').'.'.$info['extension'];
            copy($file, public_path($to));
            $res = self::save(url($to), filesize($file), basename($to), $info['extension'], 'local');
            return [
                "status" => 'ok',
                "data" => $res->path,
                'result' => $res
            ];
        }
    }
}
